﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using SharpRBM.Core;

namespace SharpRBM.DemoTools
{
    public static class LayerBitmapHelper
    {
        public const int BitmapSize = 28;
        public const int BitmapMargin = 2;
        
        public static Layer CreateLayerFromBitmap(Bitmap bitmap)
        {
            int size = bitmap.Width * bitmap.Height + 1;
            Layer layer = new Layer(size);

            bitmap.ExecuteForEachPixel(
                (Point point, Color color) =>
                {
                    layer.Values[PointToIndex(point.X, point.Y)] = (float)(color.R / 255.0);
                });

            return layer;
        }

        public static Bitmap CreateBitmapFromLayer(Layer layer)
        {
            Bitmap bitmap = new Bitmap(BitmapSize, BitmapSize);

            bitmap.SetEachPixelColour(
                (Point point) =>
                {
                    double value = layer.Values[PointToIndex(point.X, point.Y)];
                    byte b = (byte)Math.Max(0, Math.Min(255, value * 255.0));
                    return Color.FromArgb(b, b, b);
                });

            return bitmap;
        }

        public static Bitmap CreateContrastEnhancedBitmapFromLayer(Layer layer)
        {
            Bitmap bitmap = new Bitmap(BitmapSize, BitmapSize);

            double max = layer.Values.Skip(1).Max(val => val);
            double min = layer.Values.Skip(1).Min(val => val);

            if (min == max)
            {
                min = 0;
                max = 1;
            }

            bitmap.SetEachPixelColour(
                (Point point) =>
                {
                    double value = layer.Values[PointToIndex(point.X, point.Y)];
                    value = (value - min) / (max - min);
                    byte b = (byte)Math.Max(0, Math.Min(255, value * 255.0));
                    return Color.FromArgb(b, b, b);
                });

            return bitmap;
        }

        public static int PointToIndex(int x, int y)
        {
            return y * 28 + x + 1;
        }
    }
}